package com.hd.trans.utils;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.hd.trans.R;

import java.io.File;

public class ShareUtil {

    /**
     * 根据文件后缀名获得对应的MIME类型。
     *
     * @param filePath
     */
    public static String getMimeType(String filePath) {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        String mime = "text/plain";
        if (filePath != null) {
            try {
                mmr.setDataSource(filePath);
                mime = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
            } catch (IllegalStateException e) {
                return mime;
            } catch (IllegalArgumentException e) {
                return mime;
            } catch (RuntimeException e) {
                return mime;
            }
        }
        return mime;
    }

    public static String getMimeTypeFromPath(File file) {
        String ext = getExtension(file.getAbsolutePath());
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext.replace(".",""));
    }

    public static String  getExtension(String uri) {
        if (uri == null) {
            return "";
        }
        int dot = uri.lastIndexOf(".");
        if (dot >= 0) {
            return uri.substring(dot + 1);
        }
        return "";
    }

    /**
     * 系统内的分享模块
     *
     * @param mContext
     * @param title
     * @param path
     */
    public static void shareVoiceAction(Context mContext, String title, String path) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri contentUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".FileProvider", new File(path));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.putExtra(Intent.EXTRA_STREAM, contentUri);
            intent.setType("audio/mpeg");
        } else {
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(path)));
            intent.setType("audio/mpeg");
        }
        try {
            mContext.startActivity(Intent.createChooser(intent, title));
        } catch (Exception e) {
            Log.d("TAG", "分享类型报错--->" + e);
        }
    }

    /**
     * 调用系统方法 分享视频
     *
     * @param mContext
     * @param file
     * @param title
     */
    public static void shareVideo(Context mContext, File file, String title) {
        if (file == null || !file.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_SEND);
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri contentUri = getVideoContentUri(mContext, file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.putExtra(Intent.EXTRA_STREAM, contentUri);
        } else {
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
        }
        intent.setType("video/mp4");
        try {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(Intent.createChooser(intent, title));
        } catch (Exception e) {
            Toast.makeText(mContext, "分享文件不存在", Toast.LENGTH_SHORT).show();
        }
    }

    public static Uri getVideoContentUri(Context context, File file) {
        String filePath = file.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, new String[]{BaseColumns._ID},
                MediaStore.MediaColumns.DATA + "=?", new String[]{filePath}, null);
        Uri uri = null;
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex(BaseColumns._ID));
                Uri baseUri = Uri.parse("content://media/external/video/media");
                uri = Uri.withAppendedPath(baseUri, "" + id);
            }
            cursor.close();
        }
        if (uri == null) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.MediaColumns.DATA, filePath);
            uri = context.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
        }
        if (uri == null) {
            uri = FileProvider.getUriForFile(context, context.getPackageName() + ".FileProvider", file);
        }
        return uri;
    }

    // 調用系統方法分享文件
    public static void shareFile(Context context, File file, String title) {

        if (context == null) {
            return;
        }
        if (null != file && file.exists()) {
            Intent intent = new Intent(Intent.ACTION_SEND);
            //判断是否是AndroidN以及更高的版本
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".FileProvider", file);
                intent.putExtra(Intent.EXTRA_STREAM, contentUri);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setType(getMimeTypeFromPath(file));
            } else {
                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
                intent.setType(getMimeTypeFromPath(file));
            }
            try {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(Intent.createChooser(intent, title));
            } catch (Exception e) {
                Toast.makeText(context, context.getString(R.string.toast_share_failed), Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context, context.getString(R.string.toast_share_file_not_exist), Toast.LENGTH_SHORT).show();
        }
    }


    public static void shareText(Context context, String path, String title) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, path);
        intent.createChooser(intent, title);
        context.startActivity(intent);
    }
}
